import { Component, computed, Ref, ref } from 'vue'
import { SingerItem } from '@/views/singer/index.vue'
import BScroll from '@better-scroll/core'

export default (props: Readonly<{ singers: SingerItem[] }>, wrapper: Ref<HTMLElement | null>) => {
    const SHORTCART_LI_HEIGHT = 18 // 导航每一项的高度
    const scrollRef = ref<any>(null) // index-list组件中的Scroll组件的实例， 通过实例我们可以.scroll获取betterscroll滚动对象
    const titles = computed(() => props.singers.map(one => one.title))

    const touch = { index: 0, y: 0 }
    const touchStart = (e: TouchEvent) => {
        // 获取点击元素的索引
        const index = Number((e.target as HTMLElement).dataset.index)
        // 拿到scroll滚动对象，滚动到指定元素位置 scrollToElement()
        scrollToElementFn(index)
        touch.index = index
        touch.y = e.changedTouches[0].clientY
    }
    const touchMove = (e: TouchEvent) => {
        // 找到实时移动到的元素身上： 方法： Math.floor(移动的距离 / 列表项的高度) + touchstart位置索引
        const moveY = e.changedTouches[0].clientY
        let index = Math.floor((moveY - touch.y) / SHORTCART_LI_HEIGHT) + touch.index
        //  注意： 此时获取的元素有可能会超过 列表索引 的范围，所以我们要过滤下： index的取值范围 0 <= index <= titles.length - 1
        index = Math.max(0, Math.min((titles.value.length - 1), index))
        scrollToElementFn(index)
    }

    function scrollToElementFn (index: number) {
        // 拿到scroll滚动对象，滚动到指定元素位置 scrollToElement()
        const scrollToElement = wrapper.value?.children[index]
        if (scrollRef.value !== null && typeof scrollToElement !== 'undefined') {
            (scrollRef.value.scroll as BScroll).scrollToElement(scrollToElement as HTMLElement, 0, false, false)
        }
    }
    return {
        titles,
        touchStart,
        touchMove,
        scrollRef
    }
}
